package com.dataflow.example.interceptor;

import com.dataflow.example.util.Md5Util;
import com.dataflow.example.util.SaltReader;
import com.etl.dataflow.executor.core.AbstractAfterReadInterceptor;
import com.etl.dataflow.executor.element.Column;
import com.etl.dataflow.executor.element.Row;
import com.etl.dataflow.executor.element.StringColumn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("MyAfterReadInterceptor")
@Scope("prototype")
public class MyAfterReadInterceptor extends AbstractAfterReadInterceptor {

    private static final List<String> SALTS = SaltReader.readSalts();
    private static final int SALTS_SIZE = SALTS.size();

    @Override
    public void onAfterRead(Row row) {
//       log.debug("自定义AfterRead拦截器已执行, row: " + row);
        Column<?> column = row.getColumnByName("CARDNO");
        if (column != null) {
            String mpi = calcMpi(column.asString());
            row.addColumn(new StringColumn("MPI", mpi, Types.VARCHAR, "VARCHAR2"));
        }
    }

    private static String calcMpi(String cardNo) {
        int saltIndex = hash(cardNo) % SALTS_SIZE;
        String salt = SALTS.get(saltIndex);
        String cardNoAndSalt = cardNo + salt;
        return Md5Util.md5(cardNoAndSalt);
    }

    private static int hash(String cardNo) {
        int hash = cardNo.hashCode();
        // 哈希扰动
        return hash ^ (hash >>> 16);
    }

}
